#include "MyWidget.h"
#include "MyMessageBox.h"
#include <QMessageBox>
#include <QFile>
#include <QDebug>
#include <QDir>
#include <QPalette>
#include <QDesktopWidget>
#include <f32file.h>    // link against efsrv.lib
#include <apgcli.h>     // link against apgrfx.lib, apparc.lib
// #include <Restarter.h>	// link Restarter.lib

#include "mysettings.h"
#include "filelogger.h"
_LIT(MifFile, "\\resource\\apps\\StartBackup.mif");

/* Symbian C++ Code */
void MyWidget::ListDrive()
	{
	RFs iFsSession;
	User::LeaveIfError(iFsSession.Connect());
	TChar driveLetter;
	TInt driveNumber = EDriveA;
	TVolumeInfo volumeInfo;
	TDriveInfo driveInfo;

	for (; driveNumber <= EDriveZ; driveNumber++)
		{

		if (iFsSession.IsValidDrive(driveNumber))
			{
			TInt err = iFsSession.Drive(driveInfo, driveNumber);
			if (err != KErrNone)
				continue;

			if (driveInfo.iType == EMediaHardDisk)
				{
				// Insert external drives
				}
			}
		}
	iFsSession.Close();
	}

/* Symbian C++ Code */
TPtrC MyWidget::GetAppDrive(const TUid aUidApp)
	{
	RFs fs;
	RApaLsSession lsSession;

	// Connect to file server
	User::LeaveIfError(fs.Connect());
	CleanupClosePushL(fs);

	// Connect to application architecture server
	User::LeaveIfError(lsSession.Connect());
	CleanupClosePushL(lsSession);

	TApaAppInfo appInfo;
	TPtrC iDriveInstall(KNullDesC);

	// Get info on all apps, then iterate through each app  
	// and write its info (caption, name, uid) to file
	lsSession.GetAllApps();
	while (lsSession.GetNextApp(appInfo) == KErrNone)
		{
		// Get app capabilities
		TUid iUid = appInfo.iUid;
		TApaAppCapabilityBuf capability;
		lsSession.GetAppCapability(capability, iUid);
		if (capability().iAppIsHidden)
		   {
		   // Don't show hidden apps
		   continue;
		   }
		else if (iUid == aUidApp)
			{
			iDriveInstall.Set(appInfo.iFullName.Left(2)); // Copy First letter = Drive Install
			break;
			}
		}
	CleanupStack::PopAndDestroy(2); // lsSession, fs
	return iDriveInstall;
	}

/* Symbian C++ Code */
TInt MyWidget::ShowPopup(const TDesC& aMsgText, const TDesC& aHeaderText, TInt aSoftkeys)
	{
	TRequestStatus msgQueryStatus = KRequestPending;
	CAknGlobalMsgQuery *msgQueryDialog = CAknGlobalMsgQuery::NewL();
	CleanupStack::PushL(msgQueryDialog);
	// msgQueryDialog->ShowMsgQueryL(msgQueryStatus, aMsgText, aSoftkeys, aHeaderText, KNullDesC);
	msgQueryDialog->ShowMsgQueryL(msgQueryStatus, aMsgText, aSoftkeys, aHeaderText, MifFile, 16384, 16385);
	User::WaitForRequest(msgQueryStatus);
	CleanupStack::PopAndDestroy(); // msgQueryDialog
	return msgQueryStatus.Int();
	}

QString MyWidget::Version()
	{
	QString myversion = KVersion;
	return myversion;
	}

void MyWidget::InitializeComponentL()
	{
	buttonstylesheet =
					"QPushButton {color: black; font-weight: bold; background-color: rgba(255, 255, 255, 60%); padding: 2px; border-width: 1px; border-style: solid; border-color: black;}"
						"QPushButton:disabled {color: #606060; background-color: rgba(180, 180, 180, 60%); border-color: #AAAAAA;}"
						"QPushButton:pressed {color: black;}"
						"QPushButton:hover {color: black; background-color: rgba(255, 255, 255, 90%)}";

	labelstylesheet =
					"QLabel {color: black; font-weight: bold; background-color: rgba(255, 255, 255, 60%); padding: 2px; border-style: solid; border-color: black;}"
						"QLabel:hover {background-color: rgba(255, 255, 255, 90%)}";

	aboutstring.sprintf("Author: madhacker\n"
		"Support: madhacker.na@gmail.com\n"
		"Version: %.2f", Version().toFloat());

	/* Menu & Exit */
	menu = new QMenu(this);
	menu->addAction(tr("Exit"), qApp, SLOT(quit()));

	options = new QAction(tr("Options"), this);
	options->setSoftKeyRole(QAction::PositiveSoftKey);
	options->setMenu(menu);
	addAction(options);

	exit = new QAction(tr("Exit"), this);
	connect(exit, SIGNAL(triggered()), qApp, SLOT( quit() ));
	exit->setSoftKeyRole(QAction::NegativeSoftKey);
	addAction(exit);

	/* Labels & Buttons */
	label = new QLabel(tr("StartBackup"));
	label->setStyleSheet(labelstylesheet);
	// label->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);

	activate = new QPushButton(tr("Activate"));
	activate->setStyleSheet(buttonstylesheet);
	activate->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum);

	deactivate = new QPushButton(tr("Disable"));
	deactivate->setStyleSheet(buttonstylesheet);

	restore = new QPushButton(tr("Restore"));
	restore->setStyleSheet(buttonstylesheet);

	settings = new QPushButton(tr("Settings"));
	settings->setStyleSheet(buttonstylesheet);

	help = new QPushButton(tr("Help"));
	help->setStyleSheet(buttonstylesheet);

	quit = new QPushButton(tr("Quit"));
	quit->setStyleSheet(buttonstylesheet);

	labelaction = new QLabel(tr(""));
	labelaction->setStyleSheet(labelstylesheet);

	statusQT = new QLabel(tr("Status: ")); // Deprecated

	aboutme = new QLabel(aboutstring);
	aboutme->setAlignment(Qt::AlignCenter);
	aboutme->setWordWrap(true);
	aboutme->setStyleSheet(labelstylesheet);

	/* Pulsante Active */
	connect(activate, SIGNAL(clicked(bool)), this, SLOT(setActive()));
	connect(activate, SIGNAL(clicked(bool)), this, SLOT(writelabel()));

	/* Pulsante Deactivate */
	connect(deactivate, SIGNAL(clicked(bool)), this, SLOT(setDeActive()));
	connect(deactivate, SIGNAL(clicked(bool)), this, SLOT(writelabel()));

	/* Pulsante Restore */
	connect(restore, SIGNAL(clicked(bool)), this, SLOT(setRestore()));
	connect(restore, SIGNAL(clicked(bool)), this, SLOT(writelabel()));

	/* Pulsante Settings */
	connect(settings, SIGNAL(clicked()), this, SLOT(mysettings()));

	/* Pulsante Help */
	connect(help, SIGNAL(clicked()), this, SLOT(globalhelp()));

	/* Pulsante Quit */
	connect(quit, SIGNAL(clicked()), this, SLOT(closeApp()));
	}

QString MyWidget::BootCopySMSPath()
	{
	QString BootCopySMSPath = KConfigFile;
	return BootCopySMSPath;
	}

QString MyWidget::BootCopyPath()
	{
	QString BootCopyPath = KMainFile;
	return BootCopyPath;
	}

void MyWidget::resizeEvent(QResizeEvent* event)
	{
	event = 0;
	SetBackgroundImage();
	}

void MyWidget::SetBackgroundImage()
	{
	// Using QPalette you can set background image as follows.
	QPalette p = palette();

	// Load image to QPixmap, Give full path of image
	QString image = KPorImage;
	QPixmap pixmap1(image); // For emulator C: is ..\epoc32\winscw\c so image must be at that location
/*
	// resize image if it is larger than screen size.
	QDesktopWidget* desktopWidget = QApplication::desktop();
	QRect rect = desktopWidget->availableGeometry();

	QSize size(rect.width(), rect.height());
	// resize as per your requirement..
	QPixmap pixmap(pixmap1.scaled(aSize, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
*/

	p.setBrush(QPalette::Background, pixmap1);
	setPalette(p);
	}

void MyWidget::WriteOnFileL(QString filename, QString text)
	{
	QFile file(filename);
	file.open(QIODevice::WriteOnly | QIODevice::Text);
	QTextStream out(&file);
	out << text;
	__LOGSTR_TOFILE2("Writing %s on %s...", text.utf16(), filename.utf16());
	file.close();
	}

QString MyWidget::ReadOnFileL(QString filename)
	{
	QFile file(filename);
	file.open(QIODevice::ReadOnly | QIODevice::Text);
	QTextStream in(&file);
	__LOGSTR_TOFILE1("Reading from %s", filename.utf16());
	return in.readLine();
	}

void MyWidget::enableAll()
	{
	activate->setDisabled(false);
	deactivate->setDisabled(false);
	restore->setDisabled(false);
	}

void MyWidget::check()
	{
	QString temp;
	temp = ReadOnFileL(BootCopySMSPath());
	if (temp == "1")
		{
		/* Backup */
		setActive();
		}
	else if (temp == "2")
		{
		/* Restore */
		setRestore();
		}
	else
		{
		/* Disable */
		setDeActive();
		}
	writelabel();
	SetBackgroundImage();
	}

void MyWidget::globalhelp()
	{
	MyMessageBox* box =
					new MyMessageBox(
							this,
							"",
							"This application allows you to backup sensitive data (Contacts, Calendar, Browser bookmark, Notepad, Predict T9, Bluetooth list and Messages [SMS, MMS, Bluetooth]) every time the phone is starting on memory card (E:).\n\n"
								"To restore the saved data, you must select Restore from the menu and restart the phone. After this procedure the application sets automatically backup mode.");
	box->setModal(true);
	box->show(); // Deleted by Qt 4.7 rc1
	}

void MyWidget::mysettings()
	{
	MySettings* settings = new MySettings(this);
	// settings->showMaximized(); // Deleted by Qt 4.7 rc1
	settings->showFullScreen();
	}

void MyWidget::closeApp()
	{
	TInt res = ShowPopup(_L("Close StartBackup?"), _L("Exit"), R_AVKON_SOFTKEYS_YES_NO);
	if (res == EAknSoftkeyYes)
		User::Exit(0);
	}

void MyWidget::setActive()
	{
	QString temp;
	temp.sprintf("%d", ECopySMS);
	WriteOnFileL(BootCopySMSPath(), temp);
	mystring = "Backup active";
	enableAll();
	activate->setDisabled(true);
	}

void MyWidget::setDeActive()
	{
	QString temp;
	temp.sprintf("%d", EDisableSMS);
	WriteOnFileL(BootCopySMSPath(), temp);
	mystring = "Backup disabled";
	enableAll();
	deactivate->setDisabled(true);
	}

void MyWidget::setRestore()
	{
	QString temp;
	temp.sprintf("%d", ERestoreSMS);
	WriteOnFileL(BootCopySMSPath(), temp);
	mystring = "Backup to be restore";
	enableAll();
	restore->setDisabled(true);
/*	
	TInt res = ShowPopup(_L("Do you want restart?"), _L("Exit"), R_AVKON_SOFTKEYS_YES_NO);
	if (res == EAknSoftkeyYes)
		Restart();
	}

void MyWidget::Restart()
	{
	CRestarter *restart = CRestarter::NewL();
	CleanupStack::PushL(restart);
	restart->RestartL();
	CleanupStack::PopAndDestroy(restart); // restart
*/	
	}

void MyWidget::writelabel()
	{
	labelaction->setText(mystring);
	}

MyWidget::~MyWidget()
	{
	/* No need to delete any object that got a parent that is properly deleted. */
	}

void MyWidget::showbase()
	{
	
	InitializeComponentL();
	
	/* Alignment */
	layout = new QGridLayout(this);
	layout->addWidget(label, 0, 0, 1, 2, Qt::AlignHCenter | Qt::AlignTop);
	layout->addWidget(activate, 1, 0, 1, 2, (Qt::Alignment) 0x0);
	layout->addWidget(restore, 2, 0, 1, 1, (Qt::Alignment) 0x0);
	layout->addWidget(deactivate, 2, 1, 1, 1, (Qt::Alignment) 0x0);
	layout->addWidget(settings, 3, 0, 1, 2, (Qt::Alignment) 0x0);
	layout->addWidget(help, 4, 0, 1, 1, (Qt::Alignment) 0x0);
	layout->addWidget(quit, 4, 1, 1, 1, (Qt::Alignment) 0x0);
	layout->addWidget(labelaction, 5, 0, 1, 2, Qt::AlignCenter);
	layout->addWidget(aboutme, 6, 0, 1, 2, Qt::AlignHCenter | Qt::AlignBottom);

	setLayout(layout);
	
	}

void MyWidget::FirstBoot()
	{
	QString QDomain2 = KOriginalDomain2;
	QString OriginalDomain2(QDomain2);
	QString DestDomain = KDestDomain;
	QFile domain2(OriginalDomain2);
	QFile domain3;
	if (domain2.exists() && !domain3.exists(DestDomain)) // Domain2 copy if is a normal sis file
		{
		// Show alert
		__LOGSTR_TOFILE("Not SIS...");
		TInt res = ShowPopup(_L("To work properly, please copy the file from the folder domainsrv.exe c:\\data to c:\\sys\\bin"),
					_L("First boot!"),
					R_AVKON_SOFTKEYS_AGAIN_QUIT);
		if (res == EAknSoftkeyAgain)
			FirstBoot(); // Retry
		if (res == EAknSoftkeyQuit)
			User::Exit(0);
		}
	}

QString MyWidget::GetButtonSS()
	{
	return buttonstylesheet;
	}

MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent)
	{
	QString BootCopyPath = KConfigFile;
	QFile fileboot(BootCopyPath);
	
	/*********************
	 * Section for n2o4 fw
	 *********************/
	QString DestDomain = KDestDomain;
	if (!fileboot.exists()) // First Boot
		{
		__LOGSTR_TOFILE("First boot...");
		QString OriginalBoot = KOriginalBoot;
		QString OriginalDomain = KOriginalDomain;
		QString DestBoot = KDestBoot;
		QFile boot(OriginalBoot);
		QFile domain(OriginalDomain);

		if (boot.exists()) // Make Copy Boot
			{
			QFile bootDest;
                        TInt res;
                        //faenil: the following command most likely requires OPEN4ALL patch
                        if (!QDir("C:/sys/bin").exists()) {res = QDir().mkpath("C:/sys/bin"); __LOGSTR_TOFILE1("Sys/Bin MkPath: %d", res);}

			if (bootDest.exists(DestBoot)) // Remove Boot
				{
				bootDest.remove(DestBoot);
				}
                        res = boot.copy(DestBoot);
			__LOGSTR_TOFILE1("Boot1 Copy: %d", res);
			}
		if (domain.exists()) // Domain Copy
			{
			QFile domainDest;
                        TInt res;
                        //faenil: the following command most likely requires OPEN4ALL patch
                        if (!QDir("C:/sys/bin").exists()) {res = QDir().mkpath("C:/sys/bin"); __LOGSTR_TOFILE1("Sys/Bin MkPath: %d", res);}

			if (domainDest.exists(DestDomain)) // Domain Boot
				{
				domainDest.remove(DestDomain);
				}
                        res = domain.copy(DestDomain);
			__LOGSTR_TOFILE1("Domainsrv Copy: %d", res);
			}
		FirstBoot(); // Check if not in ROM
		}
		/******************
		 * End this section
		 ******************/	
	showbase();
	}
